﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;

namespace CRM.Extensions
{
    public static class HttpContextExtension
    {
        /// <summary>
        /// 获取ipv4
        /// </summary>
        /// <param name="HttpContext"></param>
        /// <returns></returns>
        public static string GetIPv4(this HttpContext HttpContext)
        {
            string[] MaybeHeaders = {
                "CLIENT_IP",//常用CND加速节点
                "CLIENT-IP",//常用CND加速节点
                "ALI_CDN_REAL_IP",//阿里云加速
                "Ali-CDN-Real-IP",//阿里云加速
                "X_FORWARDED_FOR",//标准代理头，最易被仿照
                "X-FORWARDED-FOR",//标准代理头，最易被仿照
            };

            var Header = HttpContext.Request.Headers;
            foreach (var MaybeHeader in MaybeHeaders)
            {
                string temp = null;
                if (Header.ContainsKey(MaybeHeader) && (temp = Header[MaybeHeader]).Contains("."))
                {
                    return temp;
                }
            }
            var ip = HttpContext.Connection.RemoteIpAddress?.MapToIPv4();
            return null != ip ? ip.ToString() : "0.0.0.0";
        }

        public static bool TryGetValue(this HttpRequest request, string key, out StringValues value)
        {
            if (request.Query.TryGetValue(key, out value))
            {
                return true;
            }

            return false;
        }
    }
}